//
//  PVDsListView.swift
//  GreenDeal
//
//  Created by Moennig Q on 12/12/2022.
//

import UIKit
import RxSwift
import RxCocoa
enum PVDJobStatusName: String{
    case all = "Job Status"
    case scheduled = "Scheduled"
    case installing = "Installing"
    case installed = "Installed"
    case unqualified = "Unqualified"
}
enum PVDJobStatusValue: String{
    case scheduled = "0"
    case installing = "1"
    case installed = "2"
    case unqualified = "3"
}
class PVDsListView: View {
    fileprivate lazy var disposeBag = DisposeBag()
    //MARK: - 跳转到Detail页面
    var toDetailVCClosure: ((Int,PVDsListCellOperType?)->Void)?
    //MARK: - 跳转到Job status选择页面
    var showJobStatusClosure: (()->Void)?
    //MARK: - 数据list
    var dataObserver: BehaviorRelay<[InstallationListModel]> = BehaviorRelay(value: [])
    //MARK: - top common view
    let topCommonView = MainTopCommonView()
    //MARK: - 当前筛选的Job状态
    let searchStatusLabel = ContentLabel()
    //MARK: - 当前筛选的Job type状态
    let searchJobTypeLabel = ContentLabel()
    //MARK: - list数据
    let tableView = TableView()
    //MARK: - 加载无数据的view
    lazy var loadNoDataView = LoadNoDataView()
    //MARK: - 加载失败的view
    lazy var loadFaildView = DatalLoadFaildView()
    //MARK: - 查询条件为all，且数据是0时，显示create job view
    lazy var createJobView = PVDsCreateJobView()
    override func setUpView() {
        self.backgroundColor = UIColor(hexStr: Constant.SystemBackColor)
        //top common view
        self.addSubview(topCommonView)
        topCommonView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        
        //2. table view
        self.addSubview(self.tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(topCommonView.snp.bottom).offset(-70)
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.bottom.equalToSuperview()
        }
        
        //1.3 search back view
        let searchBakView = UIView()
        searchBakView.backgroundColor = UIColor.white.withAlphaComponent(0.95)
        searchBakView.layer.cornerRadius = Constant.BackViewCornerRadius
        self.addSubview(searchBakView)
        searchBakView.snp.makeConstraints { (make) in
            make.bottom.equalTo(tableView.snp.top).offset(-25)
            make.left.equalToSuperview().offset(12)
            make.right.equalToSuperview().offset(-12)
            make.height.equalTo(40)
        }
        //1.3.1 down arrow icon
        let downArrowImageView = UIImageView(image: R.image.installation_list_search_down_arrow())
        searchBakView.addSubview(downArrowImageView)
        downArrowImageView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-16)
            make.width.height.equalTo(16)
            make.centerY.equalTo(searchBakView)
        }
        //1.3.2 status label
        searchBakView.addSubview(searchStatusLabel)
        searchStatusLabel.snp.makeConstraints { (make) in
            make.left.equalTo(16)
            make.top.equalToSuperview()
            make.right.equalTo(searchBakView.snp.centerX).offset(-32)
            make.bottom.equalToSuperview()
        }
        //verticalLineView
        let verticalLineView = View(hexStr: "#D9D9D9FF")
        searchBakView.addSubview(verticalLineView)
        verticalLineView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.height.equalTo(14)
            make.width.equalTo(1)
        }
        let jobStatusDownArrowImageView = UIImageView(image: R.image.installation_list_search_down_arrow())
        searchBakView.addSubview(jobStatusDownArrowImageView)
        jobStatusDownArrowImageView.snp.makeConstraints { (make) in
            make.right.equalTo(verticalLineView.snp.left).offset(-16)
            make.width.height.equalTo(16)
            make.centerY.equalTo(searchBakView)
        }
        //
        searchBakView.addSubview(searchJobTypeLabel)
        searchJobTypeLabel.snp.makeConstraints { (make) in
            make.left.equalTo(verticalLineView.snp.right).offset(16)
            make.top.equalToSuperview()
            make.right.equalToSuperview().offset(0)
            make.bottom.equalToSuperview()
        }
        //1.3.1 down arrow icon
        let JobTypeDownArrowImageView = UIImageView(image: R.image.installation_list_search_down_arrow())
        searchBakView.addSubview(JobTypeDownArrowImageView)
        JobTypeDownArrowImageView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-16)
            make.width.height.equalTo(16)
            make.centerY.equalTo(searchBakView)
        }
        self.tableView.drawCorner(byRoundingCorners: [.topLeft,.topRight],backColorHexStr: Constant.TransparentColorHexStr)
        self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView.showsVerticalScrollIndicator = false
        self.tableView.keyboardDismissMode = .onDrag
        //防止上拉加载时数据滚动
        self.tableView.estimatedRowHeight = 200
        self.tableView.rowHeight = UITableView.automaticDimension
        //
        self.tableView.register(InstallationListTableViewCell.self, forCellReuseIdentifier: InstallationListTableViewCell.reuseCellIdentifier)
        //设置cell信息，绑定数据源
        dataObserver.bind(to: tableView.rx.items(cellIdentifier: InstallationListTableViewCell.reuseCellIdentifier,cellType: InstallationListTableViewCell.self)){(row, model, cell) in
            cell.setData(model)
            //barcode
            cell.barcodeBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: { [weak self] _ in
                self?.toDetailVCClosure?(row, .barcode)
            }).disposed(by: cell.disposeBag)
            //checklist
            cell.checklistBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: { [weak self] _ in
                self?.toDetailVCClosure?(row, .checklist)
            }).disposed(by: cell.disposeBag)
            //signature
            cell.signatureBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: { [weak self] _ in
                self?.toDetailVCClosure?(row, .signature)
            }).disposed(by: cell.disposeBag)
        }.disposed(by: self.disposeBag)
        //选择某一行
        tableView.rx.itemSelected.bind { [weak self] (indexPath) in
            self?.toDetailVCClosure?(indexPath.row,nil)
            
        }.disposed(by: disposeBag)
        //观察数据变化，刷新数据
        dataObserver.asObservable().subscribe(onNext: {[weak self] (list) in
            self?.tableView.reloadData()
        }).disposed(by: disposeBag)
        //监听字体更改，刷新list(因为cell中对Assigned By不能自定刷新四周的padding)
        Constant.standardViewFlagSuject.subscribe {[weak self] _ in
            guard let strongSelf = self else {return }
            strongSelf.dataObserver.accept(strongSelf.dataObserver.value)
        }.disposed(by: disposeBag)
        //
        APPConfig.loginInfo.rx.observe(Bool.self, "app_create_job").subscribe(onNext: {[weak self] flag in
            self?.topCommonView.showOpertionBtns(showCreateJobBtn: (flag ?? false), showSearchBtn: true)
        }).disposed(by: self.disposeBag)
    }
    func showResultView(loadSuccessFlag: Bool, haveDataFlag: Bool = false, searchStatus: String = ""){
        //2.load faild view
        if loadSuccessFlag {//如果加载成功移除掉loadFaildView
            //没数据显示No result
            if haveDataFlag {
                self.tableView.backgroundView = nil
            }else{//搜索没有数据时
                //3.create job
                if searchStatus == PVDJobStatusName.all.rawValue && APPConfig.loginInfo.app_create_job {//搜索all数据而且有创建Job的权限，返回空就显示createJobView
                    self.tableView.backgroundView = createJobView
                }else{//不显示
                    loadNoDataView.backgroundColor = .white
                    self.tableView.backgroundView = loadNoDataView
                }
            }
            
        }else{//如果加载不成功， 显示load faild view
            self.tableView.backgroundView = loadFaildView
        }
    }
}
